package Util;

import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBUtil {
    public static MysqlDataSource dataSource=null;
    public static String URL="jdbc:mysql://localhost:3306/ojProject?characterEncoding=utf8&useSSL=true";
    public static String USER="root";
    public static String PASSWORD="123456";
    public static MysqlDataSource getDataSource(){
        if(dataSource==null){
            synchronized ((DBUtil.class)){
                if(dataSource==null){
                    dataSource=new MysqlDataSource();
                    dataSource.setURL(URL);
                    dataSource.setUser(USER);
                    dataSource.setPassword(PASSWORD);
                }
                return dataSource;
            }
        }
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return getDataSource().getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
    public static void close(Connection c, PreparedStatement s, ResultSet r){
        if(r!=null){
            try {
                r.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(s!=null){
            try {
                s.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if(c!=null){
            try {
                c.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
